package com.example.interviewrecorder.view

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.example.interviewrecorder.LyyApplicaiton
import com.example.interviewrecorder.LyyBaseActivity
import com.example.interviewrecorder.LyyDatabase
import com.example.interviewrecorder.R
import com.example.interviewrecorder.components.showTip
import com.example.interviewrecorder.dao.SecurityQuestionDao
import com.example.interviewrecorder.databinding.ActivityEditSecurityQuestionBinding
import com.example.interviewrecorder.model.SecurityQuestion
import com.example.interviewrecorder.utils.LyyActivityCollector
import com.example.interviewrecorder.utils.LyyLogUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class EditSecurityQuestionActivity : LyyBaseActivity(), View.OnClickListener {
    private val mBinding: ActivityEditSecurityQuestionBinding by lazy {
        ActivityEditSecurityQuestionBinding.inflate(layoutInflater)
    }
    private val securityQuesitonDao: SecurityQuestionDao =
        LyyDatabase.getDatabase().getSecurityQuestionDao()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(mBinding.root)
        initEvents()
        initData()
    }

    private fun initData() {
        lifecycleScope.launch {
            launch(Dispatchers.IO){
                val currUser=LyyApplicaiton.currUser
                currUser?.let {
                    runCatching {
                        val list = securityQuesitonDao.querySQByUserId(it.id)
                        runOnUiThread {
                            val securityQuesitonOne=list[0]
                            val securityQuesitonTwo=list[1]
                            val securityQuesitonThree=list[2]

                            mBinding.questionOneRight.setText(securityQuesitonOne.quesiton)
                            mBinding.answerOneRight.setText(securityQuesitonOne.answer)
                            mBinding.questionTwoRight.setText(securityQuesitonTwo.quesiton)
                            mBinding.answerTwoRight.setText(securityQuesitonTwo.answer)
                            mBinding.questionThreeRight.setText(securityQuesitonThree.quesiton)
                            mBinding.answerThreeRight.setText(securityQuesitonThree.answer)
                        }
                    }.onFailure {
                        LyyLogUtil.e(TAG,"initData() fail ...")
                    }

                }
            }
        }
    }

    private fun initEvents() {
        mBinding.saveBtn.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.saveBtn -> {
                saveSecurityQuestion()
            }
        }
    }

    private fun saveSecurityQuestion() {
        val questionOne = mBinding.questionOneRight.text.toString()
        val answerOne = mBinding.answerOneRight.text.toString()
        val questionTwo = mBinding.questionTwoRight.text.toString()
        val answerTwo = mBinding.answerTwoRight.text.toString()
        val questionThree = mBinding.questionThreeRight.text.toString()
        val answerThree = mBinding.answerThreeRight.text.toString()

        if (!questionOne.isNotBlank() && !answerOne.isNotBlank() && !questionTwo.isNotBlank() && !answerTwo.isNotBlank() && !questionThree.isNotBlank() && !answerThree.isNotBlank()) {
            insertSecurityQuestions(
                questionOne,
                answerOne,
                questionTwo,
                answerTwo,
                questionThree,
                answerThree
            )
        } else if (questionOne.isNotBlank() && answerOne.isNotBlank() && questionTwo.isNotBlank() && answerTwo.isNotBlank() && questionThree.isNotBlank() && answerThree.isNotBlank()) {
            insertSecurityQuestions(
                questionOne,
                answerOne,
                questionTwo,
                answerTwo,
                questionThree,
                answerThree
            )
        } else {
            showTip(content = getString(R.string.input_security_question_and_answer_tip))
        }
    }

    private fun insertSecurityQuestions(
        questionOne: String,
        answerOne: String,
        questionTwo: String,
        answerTwo: String,
        questionThree: String,
        answerThree: String
    ) {
        lifecycleScope.launch {
            launch(Dispatchers.IO) {
                repeatOnLifecycle(Lifecycle.State.STARTED) {
                    val currUser = LyyApplicaiton.currUser
                    currUser?.let {
                        val currTime = System.currentTimeMillis()

                        runCatching {
                            //开启事务
                            LyyDatabase.getDatabase().runInTransaction {
                                //先删除当前用户的所有密保问题
                                securityQuesitonDao.deleteAllSecurityQuestionById(it.id)

                                //再执行插入操作
                                val securityQuestion1 = SecurityQuestion(
                                    it.id,
                                    questionOne,
                                    answerOne,
                                    currTime,
                                    currTime
                                )
                                securityQuesitonDao.insertSecurityQuestion(securityQuestion1)

                                val securityQuestion2 = SecurityQuestion(
                                    it.id,
                                    questionTwo,
                                    answerTwo,
                                    currTime,
                                    currTime
                                )
                                securityQuesitonDao.insertSecurityQuestion(securityQuestion2)

                                val securityQuestion3 = SecurityQuestion(
                                    it.id,
                                    questionThree,
                                    answerThree,
                                    currTime,
                                    currTime
                                )
                                securityQuesitonDao.insertSecurityQuestion(securityQuestion3)
                            }
                        }.onSuccess {
                            runOnUiThread {
                                showTip(content = getString(R.string.save_security_question_success_tip))
                            }
                        }.onFailure {
                            LyyLogUtil.e(TAG, it.toString())
                        }
                    }
                }
            }
        }
    }

    companion object {
        private const val TAG = "EditSecurityQuestionAct"
        fun start() {
            val currAct = LyyActivityCollector.getCurrActivity()
            val intent = Intent(currAct, EditSecurityQuestionActivity::class.java)
            currAct.startActivity(intent)
        }
    }
}